<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body></body>
  <script>
    // var exrp = new Date('2022-3-25 09:29:00')
    // document.cookie = 'mimngzi=张三;expires=' + exrp

    //设置cookie
    function setCookie(cname, cvalue, exdays) {
      var d = new Date()
      d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000)
      var expires = 'expires=' + d.toUTCString()
      document.cookie = cname + '=' + cvalue + '; ' + expires
    }
    // setCookie('dongyangguang', 'guangyangdong', 8)
    // setCookie('xiaowang', 'wangxiao', 3)
    // setCookie('xiaowang', 'wangxiao', 3)

    //获取cookie
    function getCookie(cname) {
      var name = cname + '=' //xiaowang=
      var ca = document.cookie.split(';')
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim() //去除字符串两边空格
        if (c.indexOf(name) == 0) {
          return c.substring(name.length, c.length)
        }
      }
      return ''
    }
    console.log(getCookie('xiaowang'))

    //
    function checkCookie() {
      var user = getCookie('username')
      if (user != '') {
        alert('欢迎 ' + user + ' 再次访问')
      } else {
        user = prompt('请输入你的名字:', '')
        if (user != '' && user != null) {
          setCookie('username', user, 30)
        }
      }
    }
    checkCookie()
  </script>
</html>
